package com.educhains.web.ctrl.frontend;

import com.educhains.module.activity.service.ActivityService;
import com.educhains.module.activity.vo.mb_model.Activity;
import com.educhains.module.blog.service.BlogService;
import com.educhains.module.blog.vo.Blog;
import com.educhains.module.blog.vo.BlogReply;
import com.educhains.module.post.service.PostReplyService;
import com.educhains.module.post.service.PostService;
import com.educhains.module.post.vo.Post;
import com.educhains.module.post.vo.PostReply;
import com.educhains.module.user.service.UserService;
import com.educhains.module.user.service.UserWalletService;
import com.educhains.module.user.vo.User;
import com.educhains.module.user.vo.UserWallet;
import com.educhains.web.util.FileUploadUtils;
import com.educhains.web.util.PropertyUtils;
import com.educhains.web.util.SessionUtils;
import com.educhains.web.util.StringUtils;
import org.apache.ibatis.session.RowBounds;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.imageio.ImageIO;
import javax.imageio.ImageReadParam;
import javax.imageio.ImageReader;
import javax.imageio.stream.ImageInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.awt.image.CropImageFilter;
import java.awt.image.FilteredImageSource;
import java.awt.image.ImageFilter;
import java.io.File;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
 * @author YuRun
 * @since 2017年8月31日
 */

@Controller
@RequestMapping("/personalCenter")
public class PersonalCenterCtrl {

    @Autowired
    private UserWalletService userWalletService = null;

    @Autowired
    private ActivityService activityService = null;

    @Autowired
    private BlogService blogService = null;

    @Autowired
    private PostReplyService postReplyService = null;

    @Autowired
    private PostService postService = null;

    @Autowired
    private UserService userService = null;

    /**
     * Index
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "/index/{id}", method = RequestMethod.GET)
    public String index(HttpServletRequest request, @PathVariable String id) {
        // User user = SessionUtils.getUser(request);

        User user = userService.selectUserById(id);
//        String userEmail = user.getUserEmail();
//        User dbUser = userService.getUserByEmail(userEmail);
//        SessionUtils.removeAttribute(request, User.USER_SESSION_KEY);
//        SessionUtils.setUser(request, dbUser);
        List<Activity> activityList = activityService.getActivityListByUserIdWithLimit(user.getUserId(), 5);
        List<Post> postList = postService.getPostListByUserIdWithLimit(user.getUserId(), 5);
        List<Blog> blogList = blogService.getBlogListByUserIdWithLimit(user.getUserId(), 5);
        List<BlogReply> blogReplyList = blogService.getBlogReplyListByUserIdWithLimit(user.getUserId(), 5);
        List<PostReply> postReplyList = postReplyService.getPostReplyListByUserIdWithLimit(user.getUserId(), 5);

        request.setAttribute("user", user);
        request.setAttribute("activityList", activityList);
        request.setAttribute("postList", postList);
        request.setAttribute("blogList", blogList);
        request.setAttribute("blogReply", blogReplyList);
        request.setAttribute("postReply", postReplyList);
        return "/frontend/personalCenter/index";
    }

    @RequestMapping(value = "/uploadUserPhoto", method = RequestMethod.POST)
    public String uploadHeadImage(
            HttpServletRequest request,
            @RequestParam(value = "imgFile") MultipartFile imageFile
    ) throws Exception {
        System.out.println("==========Start=============");
        String x = request.getParameter("x");
        String y = request.getParameter("y");
        String h = request.getParameter("h");
        String w = request.getParameter("w");
        String realPath = request.getSession().getServletContext().getRealPath("/");

        String resourcePath = "resources/uploadImages/";

        if (imageFile != null) {
            if (FileUploadUtils.allowUpload(imageFile.getContentType())) {
                String fileName = FileUploadUtils.rename(imageFile.getOriginalFilename());
                int end = fileName.lastIndexOf(".");
                String saveName = fileName.substring(0, end);
                File dir = new File(realPath + resourcePath);
                if (!dir.exists()) {
                    dir.mkdirs();
                }
                File file = new File(dir, saveName + "_src.jpg");
                imageFile.transferTo(file);
                String srcImagePath = realPath + resourcePath + saveName;
                System.out.println(srcImagePath);
                int imageX = Integer.parseInt(x);
                int imageY = Integer.parseInt(y);
                int imageH = Integer.parseInt(h);
                int imageW = Integer.parseInt(w);
                //这里开始截取操作
                System.out.println("==========imageCutStart=============");
                System.out.println(imageX);
                System.out.println(imageY);
                System.out.println(imageW);
                System.out.println(imageH);
                imgCut(srcImagePath, imageX, imageY, imageW, imageH);
                System.out.println("==========imageCutEnd=============");
//                request.getSession().setAttribute("imgSrc",resourcePath + saveName+"_src.jpg");//成功之后显示用
//                request.getSession().setAttribute("imgCut",resourcePath + saveName+"_cut.jpg");//成功之后显示用
                String path = resourcePath + saveName + "_cut.jpg";
                System.out.println(path);
                User sessionUser = SessionUtils.getUser(request);
                sessionUser.setUserPhoto(path);
                userService.updateUserPhoto(sessionUser);
            }
        }
        return "frontend/personalCenter/index";
    }

    public static void imgCut(String srcImageFile, int x, int y, int desWidth,
                              int desHeight) {
        try {
            Image img;
            ImageFilter cropFilter;
            BufferedImage bi = ImageIO.read(new File(srcImageFile + "_src.jpg"));
            int srcWidth = bi.getWidth();
            int srcHeight = bi.getHeight();
            if (srcWidth >= desWidth && srcHeight >= desHeight) {
                Image image = bi.getScaledInstance(srcWidth, srcHeight, Image.SCALE_DEFAULT);
                cropFilter = new CropImageFilter(x, y, desWidth, desHeight);
                img = Toolkit.getDefaultToolkit().createImage(
                        new FilteredImageSource(image.getSource(), cropFilter));
                BufferedImage tag = new BufferedImage(desWidth, desHeight,
                        BufferedImage.TYPE_INT_RGB);
                Graphics g = tag.getGraphics();
                g.drawImage(img, 0, 0, null);
                g.dispose();
                //输出文件
                ImageIO.write(tag, "JPEG", new File(srcImageFile + "_cut.jpg"));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
